package com.bookcloud.java21.chapter8.线程间通讯88;

public class ThreadCommunication {
  public static void main(String[] args) {
    Message message = new Message();

    // 写线程
    Thread writer =
        new Thread(
            new Runnable() {
              @Override
              public void run() {
                String[] messages = {"第一条消息", "第二条消息", "第三条消息", "第四条消息", "结束"};

                for (String msg : messages) {
                  message.write(msg);

                  try {
                    Thread.sleep(1000);
                  } catch (InterruptedException e) {
                    e.printStackTrace();
                  }
                }
              }
            },
            "写线程");

    // 读线程
    Thread reader =
        new Thread(
            new Runnable() {
              @Override
              public void run() {
                for (String msg = message.read(); !msg.equals("结束"); msg = message.read()) {
                  try {
                    Thread.sleep(1000);
                  } catch (InterruptedException e) {
                    e.printStackTrace();
                  }
                }
                System.out.println("读线程结束");
              }
            },
            "读线程");

    writer.start();
    reader.start();
    try {
      writer.join();
      reader.join();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    System.out.println("主线程结束");
  }
}
